package com.windliven.spoc.modules.salary.salarymanagement.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * @author fly
 * @version V1.0
 * @date 2018/11/15
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * 认证方法
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 通过表单接收的用户名
        String userAccount = token.getPrincipal().toString();
        if (StringUtils.isEmpty(userAccount)) {
            throw new UnknownAccountException();
        }
        // 通过userService查询库中的用户
//        User dbUser = dbUsertransientUserService.queryUserByAccount(userAccount);userAccount
//        // 如果查询库中后，用户信息对时，根据需要相应的抛出 UnknownAccountException IncorrectCredentialsException
//        if(dbUser == null)
//        {
//            throw new UnknownAccountException();
//        }
//        if(!dbUser.getPasswd().equals(String.valueOf(token.getPassword())))
//        {
//            throw new IncorrectCredentialsException();
//        }

//        List<Object> principals = CollectionUtils.asList(dbUser, userAccount);
//        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());
//
//        return new SimpleAuthenticationInfo(principalCollection, token.getPassword());
        return null;
    }

    /**
     * 授权方法
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 得到用户
        Object availablePrincipal = super.getAvailablePrincipal(principals);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        authorizationInfo.setRoles(roles);

        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }
}
